package com.example.aicode.chat;


import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AiCodeHelper {

    @Resource
    private ChatModel qwenChatModel;

    private static final String PROMPT_TEMPLATE = """ 
            你是「Java六边形战士」：
            - 刷题：LeetCode 3000+ 题解作者，周赛排名前 1%。
            - 工程：10 年 Java/SpringCloud/MyBatis/JDK17 经验，主导过日均 10 亿级调用系统。
            - 面试：BAT 面试官 6 年，熟悉八股、场景、算法、JVM、分布式、高并发、系统设计。
            - 技术栈：Spring Boot 3.x / Spring Cloud / MyBatis-Plus / Netty / Redis / Kafka / MySQL 8 / OceanBase / Docker / K8s。
            """;

    /**
     * 基础的聊天
     * @param message
     * @return
     */
    public String chat(String message) {
        UserMessage userMessage = UserMessage.from(message);
        log.info("request: {}", userMessage);

        ChatResponse chatResponse;
        try {
            chatResponse = qwenChatModel.chat(userMessage);
            log.info("response: {}", chatResponse);
            return chatResponse.aiMessage().text();
        } catch (Exception e) {
            log.error("Error occurred while processing chat request", e);
            throw new RuntimeException("Failed to get response from QwenChatModel", e);
        }
   }

    /**
     * 图片解析
     * @param userMessage
     * @return
     */
    public String chatWithMessage(UserMessage userMessage) {
        log.info("request: {}", userMessage);

        ChatResponse chatResponse;
        try {
            chatResponse = qwenChatModel.chat(userMessage);
            log.info("response: {}", chatResponse);
            return chatResponse.aiMessage().text();
        } catch (Exception e) {
            log.error("Error occurred while processing chat request", e);
            throw new RuntimeException("Failed to get response from QwenChatModel", e);
        }
    }

    /**
     * 提示词
     * @param message
     * @return
     */
    public String chatWithPrompt(String message) {
        SystemMessage systemMessage = SystemMessage.from(PROMPT_TEMPLATE);
        UserMessage userMessage = UserMessage.from(message);
        log.info("request: {}", userMessage);

        ChatResponse chatResponse;
        try {
            chatResponse = qwenChatModel.chat(systemMessage,userMessage);
            log.info("response: {}", chatResponse);
            return chatResponse.aiMessage().text();
        } catch (Exception e) {
            log.error("Error occurred while processing chat request", e);
            throw new RuntimeException("Failed to get response from QwenChatModel", e);
        }
    }
}
